package kayao.server.threads;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

import kayao.common.KayaoValues;
import kayao.common.NetworkUtils;
import kayao.server.DesktopServer;

public class TimeThread extends Thread {
	
	private String mAddress=null;
	private int mPort;
	private DatagramSocket mSocket=null;
	private byte []mDataReceived=null;
	
	public TimeThread(String client, int port, DatagramSocket socket) {
		mAddress = client;
		mPort = port;
		mSocket = socket;
	}

	public void run()
	{
		try
		{
			// Create the array with data to send
			byte[] data = new byte[5];
			data[0] = KayaoValues.TIME_IS_MESSAGE;
			int uptime = (int) (System.currentTimeMillis()-KayaoValues.SERVER_START.getTime());
			NetworkUtils.insertIntToByteArray(data, 1, uptime);
			//Send the answer packet
			InetAddress address = InetAddress.getByName(mAddress);
			mSocket.send(new DatagramPacket(data, data.length, address, mPort));
			System.out.println(DesktopServer.getTimestamp()+" [Server] Time request answered with " + data.length +" bytes.\n");
		}
		catch(Exception e)
		{
			//Basic treatment at the moment... show message and restart the reading
			e.printStackTrace();
			System.out.println("TimeThread Error: "+ e.getMessage());
			//Some exceptions...
		}
	}	
}
